package com.edu.hre.common.email;

import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.Constants;
import com.edu.hre.common.utils.ServerConfig;

public class EMailSender {
	
	public static final String BEAN_NAME = "eMailSender"; 
	private ServerConfig serverConfig = null;
	
	public static void main(String []args){
		try {
			String defaultEmail = "hcns.hrentry@gmail.com";
			String defaultPass = "@xlmb2012@";
			new EMailSender().sendMail(new String[]{"ducb89@yahoo.com"}, "TEST3", "HI", false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendMail(final List<EMailObject> listObjs){
		try {
			Constants.executor.execute(new Runnable() {
				public void run() {
					sendMail(serverConfig.getDefaultAddressEmail(), serverConfig.getDefaultPassEmail(), listObjs);
				}
			});
		} catch (Exception e) {
			CommonUtils.println(e.getMessage());
		}
	}

	public void sendMail(final String recipients[],final String subject, final String content, final boolean isHTMLStyle) {
		try {
			Constants.executor.execute(new Runnable() {
				public void run() {
					sendMail(serverConfig.getDefaultAddressEmail(), serverConfig.getDefaultPassEmail(), recipients, subject, content, isHTMLStyle);
				}
			});
		} catch (Exception e) {
			CommonUtils.println(e.getMessage());
		} 
	}
	
	private void sendMail(final String from, final String pass, List<EMailObject> listObjs){
		Session session = getSession(from, pass);
		for(int i = 0; listObjs != null && i < listObjs.size(); i ++){
			try {
				EMailObject obj = listObjs.get(i);
				Message msg = new MimeMessage(session);
				msg.setFrom(new InternetAddress(from));
				msg.setRecipient(Message.RecipientType.TO, new InternetAddress(obj.getAddress()));
				msg.setSubject(obj.getSubject());
				if (obj.isHTMLStyle()) {
					msg.setContent(obj.getContent(), "text/html; charset=UTF-8");
				} else {
					msg.setText(obj.getContent());
				}
				msg.setSentDate(new Date());
				Transport.send(msg);
				CommonUtils.println("A message sent.");
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
		CommonUtils.println("Done!");
	}
	
	private void sendMail(String from, String pass, String recipients[], 
				String subject, String content, boolean isHTMLStyle) {
		// -- Create a new message --
		try {
			Message msg = new MimeMessage(getSession(from, pass));
			msg.setFrom(new InternetAddress(from));
			InternetAddress[] addressTo = new InternetAddress[recipients.length];
			for (int i = 0; i < recipients.length; i++) {
				addressTo[i] = new javax.mail.internet.InternetAddress(recipients[i]);
			}
			msg.setRecipients(Message.RecipientType.TO, addressTo);
			msg.setSubject(subject);
			if (isHTMLStyle) {
				msg.setContent(content, "text/html; charset=UTF-8");
			} else {
				msg.setText(content);
			}
			msg.setSentDate(new Date());
			// **************** Without Attachments ******************
			Transport.send(msg);
			CommonUtils.println("Message sent.");
		} catch (Exception e) {
			CommonUtils.println(e.getMessage());
		}
	}
	
	private Session getSession(final String from, final String pass){
		Properties props = System.getProperties();
		props.setProperty("mail.smtp.host", "smtp.gmail.com");
		// ******************** FOR PROXY ******************
		// props.setProperty("proxySet","true");
		// props.setProperty("socksProxyHost","proxy");
		// props.setProperty("socksProxyPort","8080");
		// props.setProperty("socksProxyVersion","5");
		// ******************** FOR PROXY ******************
		
		props.put("mail.smtp.user", "username");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "25");
		// props.put("mail.debug", "true");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.EnableSSL.enable", "true");
		props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.port", "465");
		props.setProperty("mail.smtp.socketFactory.port", "465");
		Session session = Session.getDefaultInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(from, pass);
			}
		});
		return session;
	}

	public ServerConfig getServerConfig() {
		return serverConfig;
	}

	public void setServerConfig(ServerConfig serverConfig) {
		this.serverConfig = serverConfig;
	} 
}
